import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:wheel_of_fortune/model/address_model.dart';
import 'package:wheel_of_fortune/model/rotary_table_model.dart';
import 'package:wheel_of_fortune/model/user_address_model.dart';
import 'package:wheel_of_fortune/product/add_address_page.dart';
import 'package:wheel_of_fortune/provider/product_provider.dart';
import 'package:wheel_of_fortune/utils/utils.dart';
import 'package:wheel_of_fortune/widgets/message_alerts.dart';
import 'package:wheel_of_fortune/widgets/provider_widget.dart';

import 'widgets/address_button.dart';
import 'widgets/address_item.dart';

class ProductWinPage extends StatefulWidget {
  final PrizeInfos prize;
  final String lotteryId;
  ProductWinPage(this.prize, this.lotteryId, {Key key}) : super(key: key);

  @override
  _ProductWinPageState createState() => _ProductWinPageState();
}

class _ProductWinPageState extends State<ProductWinPage> {
  UserAddressModel userAddressModel;
  ProductProvider _provider;

  _showVerified() async {
    bool back = await showModalBottomSheet(
      context: context,
      enableDrag: false,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (c) {
        return AlertDialog(
          titlePadding: EdgeInsets.zero,
          title: MessageAlerts(
            type: 1,
            content:
                'You are not yet verified user,\nplease upgrade your account to\nEstablished to collect your gift.',
          ),
        );
      },
    );
    if(back){
      /// TODO - jump to verified user
    }else{
      /// give up gift
      await _provider.giveUpPrize(widget.lotteryId);
      showToast(msg: 'You have given up collecting your gift.');
      Navigator.of(context).pop();
    }
  }
  _addOrEditAddress({int index})async{
    
    UserAddressModel model;
    if (index!=null) {
      model = _provider.addressList[index];
    }
    List value = await showModalBottomSheet(
      context: context,
      enableDrag: false,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (c) {
        return AddAddressPage(userAddressModel: model,);
      },
    );
    if (value!=null && value.length>0) {
      if (index!=null) {
        _provider.editAddress(index, value);
      }else{
        _provider.addAddress(value);
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    var left = 41.0;
    return ProviderWidget<ProductProvider>(
      model: ProductProvider(),
      onModelReady: (p) => p.initData(),
      builder: (c, provider, child) {
        _provider = provider;
        return WillPopScope(
          onWillPop: () async {
            final back = await showModalBottomSheet(
              context: context,
              // enableDrag: false,
              isScrollControlled: true,
              backgroundColor: Colors.transparent,
              builder: (c) {
                return AlertDialog(
                  titlePadding: EdgeInsets.zero,
                  title: MessageAlerts(
                    type: 0,
                    content: 'Are you sure to give up your gift?',
                  ),
                );
              },
            );
            if (back) {
              await provider.giveUpPrize(widget.lotteryId);
              showToast(msg: 'You have given up collecting your gift.');
            }
            return back;
          },
          child: Scaffold(
            appBar: AppBar(
              title: Text(
                'Collect Gift',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w400,
                ),
              ),
              centerTitle: true,
            ),
            body: Stack(
              children: [
                Positioned(
                  left: 0,right: 0,top: 0,bottom: 94,
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.fromLTRB(left, 42, left, 0),
                          child: InkWell(
                            onTap: _showVerified,
                            child: Text(
                              "Choose your\nDelivery Address",
                              strutStyle: StrutStyle(forceStrutHeight: true,fontSize: 30, leading: 0.3),
                              style: TextStyle(
                                color: mainColor,
                                fontSize: 30,
                                fontFamily: 'Avenir Next LT Pro',
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          )
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(left, 20, left, 20),
                          child: InkWell(
                            onTap: _showVerified,
                            child: Text(
                              'Please choose address and make sure\nthe address is correct otherwise,\nyou might not be able to receive your gift.',
                              style: TextStyle(
                                color: mainColor,
                                fontSize: 12,
                                fontFamily: 'Avenir Next LT Pro',
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(left, 0, left, 0),
                          child: Text(
                            'Adress',
                            style: TextStyle(
                              color: grey6EColor,
                              fontSize: 11,
                              fontFamily: 'Avenir Next LT Pro',
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        // 地址选择
                        Container(
                          margin: EdgeInsets.fromLTRB(left - 2, 10, left - 15, 0),
                          child: Column(
                            children: List.generate(provider.addressList.length, (index) {
                              final model = provider.addressList[index];
                              return AddressItem(
                                type: model.user == null?1:0,
                                model: model,
                                onSelect: (){
                                  provider.selectAddressWithIndex(index);
                                },
                                onEdit: ()async{
                                  provider.selectAddressWithIndex(index);
                                  _addOrEditAddress(index: index);
                                },
                              );
                            }),
                          ),
                        ), 
                        // 添加地址的按钮
                        Container(
                          margin: EdgeInsets.fromLTRB(left, 0,left,20),
                          child: AddressButton(
                            width: Utils.screenWidth - 2*left,
                            onTap: () async {
                              _addOrEditAddress();
                            }
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                /// Collect
                Positioned(
                  left: 0,right: 0,bottom: 0,
                  child: Container(
                    margin: EdgeInsets.fromLTRB(
                      (Utils.screenWidth - 20 * 2 - 184) / 2,
                      0,
                      (Utils.screenWidth - 20 * 2 - 184) / 2,
                      0,
                    ),
                    child: GestureDetector(
                      onTap: () async {
                        var re;
                        UserAddressModel addressModel;
                        provider.addressList.forEach((element) {
                          if (element.selectAddress) {
                            addressModel = element;
                          }
                        });
                        if (addressModel != null) {
                          re = await provider.collectPrize(
                            widget.lotteryId,
                            address: addressModel.address,
                            provinceId: addressModel.provinceId,
                            provinceName: addressModel.provinceName,
                            cityMunicipalityId: addressModel.cityMunicipalityId,
                            cityName: addressModel.cityName,
                          );
                        } else {
                          re = await provider.collectPrize(widget.lotteryId);
                        }
                        if (re == 'success') {
                          showToast(msg: 'Successfully Collected\nyour gift will be delivered ASAP');
                          Navigator.of(context).pop();
                        } else if (re['status'] == 2003) {
                          _showVerified();
                        }
                      },
                      child: Container(
                        height: 34,
                        margin: EdgeInsets.only(bottom: 40),
                        decoration: BoxDecoration(
                          color: Color(0xFFFFB32C),
                          borderRadius: BorderRadius.circular(17),
                        ),
                        child: Center(
                          child: Text(
                            'Submit',
                            style: TextStyle(
                                color: Color(0xFFFFFFFF),
                                fontSize: 14,
                                fontFamily: 'Avenir Next LT Pro',
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
